﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MyK3CloudCore.IOC.K3Client;

public class K3CloudApiSdk
{
    public static async Task<string> PostJsonAsync(string service_url, string sContent = "")
    {
        var path_url = service_url;
        if (service_url.StartsWith("http"))
        {
            var p_index = service_url.IndexOf("/", 10);
            if (p_index > -1)
            {
                path_url = service_url[p_index..];
            }
        }
        path_url = path_url.Replace("/", "%2F");
        var arr = K3IOCServiceCollectionExtensions.Configs.AppID.Split("_");
        var clientId = arr[0];
        var client_sec = KingdeeSignature.DecryptAppSecret(arr[1]);
        var timestamp = DateTimeFormatUtils.CurrentTimeSeconds().ToString();
        var nonce = timestamp;
        var api_sign = "POST\n" + path_url + "\n\nx-api-nonce:" + nonce + "\nx-api-timestamp:" + timestamp + "\n";
        var app_data = $"{K3IOCServiceCollectionExtensions.Configs.AcctId},{K3IOCServiceCollectionExtensions.Configs.UserName},{K3IOCServiceCollectionExtensions.Configs.LCID},0";
        var api_signature = KingdeeSignature.HmacSHA256(api_sign, client_sec, Encoding.UTF8, true);
        var kd_signature = KingdeeSignature.HmacSHA256(K3IOCServiceCollectionExtensions.Configs.AppID + app_data, K3IOCServiceCollectionExtensions.Configs.AppSecret, Encoding.UTF8, true);
        using HttpClient client = K3IOCServiceCollectionExtensions.HttpClientFactory.CreateClient(IocConst.K3WEBAPI_CLIENT);
        client.DefaultRequestHeaders.Add("X-Api-ClientID", clientId);
        client.DefaultRequestHeaders.Add("X-Api-Auth-Version", "2.0");
        client.DefaultRequestHeaders.Add("x-api-timestamp", timestamp);
        client.DefaultRequestHeaders.Add("x-api-nonce", nonce);
        client.DefaultRequestHeaders.Add("x-api-signheaders", "x-api-timestamp,x-api-nonce");
        client.DefaultRequestHeaders.Add("X-Api-Signature", api_signature);
        client.DefaultRequestHeaders.Add("X-Kd-Appkey", K3IOCServiceCollectionExtensions.Configs.AppID);
        client.DefaultRequestHeaders.Add("X-Kd-Appdata", Convert.ToBase64String(Encoding.UTF8.GetBytes(app_data)));
        client.DefaultRequestHeaders.Add("X-Kd-Signature", kd_signature);
        client.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78");

        HttpContent stringContent = new StringContent(sContent);
        stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        var result = await client.PostAsync(service_url, stringContent);
        result.EnsureSuccessStatusCode();
        return ValidateResult(await result.Content.ReadAsStringAsync());
    }

    private static string ValidateResult(string responseText)
    {
        if (responseText.StartsWith("response_error:", StringComparison.OrdinalIgnoreCase))
        {
            return responseText.TrimStart("response_error:".ToCharArray());
        }
        return responseText;
    }

    /// <summary>
    /// 数据中心
    /// </summary>
    public static async Task<string> GetDataCenters()
    {
        return await Execute("Kingdee.BOS.ServiceFacade.ServicesStub.Account.AccountService.GetDataCenterList");
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    public static async Task<string> SendMsg(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.SendMsg", data);
    }
    /// <summary>
    /// 保存
    /// </summary>
    public static async Task<string> Save(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save", formid, data);
    }

    /// <summary>
    /// 批量保存
    /// </summary>
    public static async Task<string> BatchSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave", formid, data);
    }

    /// <summary>
    /// 审核
    /// </summary>
    public static async Task<string> Audit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit", formid, data);
    }

    /// <summary>
    /// 删除
    /// </summary>
    public static async Task<string> Delete(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete", formid, data);
    }

    /// <summary>
    /// 反审核
    /// </summary>
    public static async Task<string> UnAudit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit", formid, data);
    }

    /// <summary>
    /// 提交
    /// </summary>
    public static async Task<string> Submit(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit", formid, data);
    }

    /// <summary>
    /// 查看
    /// </summary>
    public static async Task<string> View(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View", formid, data);
    }

    /// <summary>
    /// 单据查询
    /// </summary>
    public static async Task<string> ExecuteBillQuery(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery", data);
    }

    /// <summary>
    /// 暂存
    /// </summary>
    public static async Task<string> Draft(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft", formid, data);
    }

    /// <summary>
    /// 分配
    /// </summary>
    public static async Task<string> Allocate(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate", formid, data);
    }

    /// <summary>
    /// 弹性域保存
    /// </summary>
    public static async Task<string> FlexSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.FlexSave", formid, data);
    }

    /// <summary>
    /// 下推
    /// </summary>
    public static async Task<string> Push(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push", formid, data);
    }

    /// <summary>
    /// 分组保存
    /// </summary>
    public static async Task<string> GroupSave(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupSave", formid, data);
    }

    /// <summary>
    /// 拆单
    /// </summary>
    public static async Task<string> Disassembly(string formid, object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Disassembly", formid, data);
    }

    /// <summary>
    /// 查询单据接口
    /// </summary>
    public static async Task<string> QueryBusinessInfo(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo", data);
    }

    /// <summary>
    /// 查询分组信息接口
    /// </summary>
    public static async Task<string> QueryGroupInfo(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryGroupInfo", data);
    }

    /// <summary>
    /// 工作流审批
    /// </summary>
    public static async Task<string> WorkflowAudit(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.WorkflowAudit", data);
    }

    /// <summary>
    /// 分组删除接口
    /// </summary>
    public static async Task<string> GroupDelete(object data)
    {
        return await Execute("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupDelete", data);
    }

    /// <summary>
    /// 操作接口
    /// </summary>
    /// <param name="formid">业务对象表单Id</param>
    /// <param name="opNumber">操作编码</param>
    /// <param name="data">数据</param>
    public static async Task<string> ExcuteOperation(string formid, string opNumber, object data)
    {
        return await PostJsonAsync($"{K3IOCServiceCollectionExtensions.Configs.ServerHost}/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc", JsonConvert.SerializeObject(new { formid, opNumber, data }));
    }

    /// <summary>
    /// 自定义接口
    /// </summary>
    public static async Task<string> Execute(string servername, object data = null)
    {
        return await PostJsonAsync($"{K3IOCServiceCollectionExtensions.Configs.ServerHost}/{servername}.common.kdsvc", data == null ? "" : JsonConvert.SerializeObject(new { data }));
    }

    public static async Task<string> Execute(string servername, string formid, object data = null)
    {
        return await PostJsonAsync($"{K3IOCServiceCollectionExtensions.Configs.ServerHost}/{servername}.common.kdsvc", data == null ? "" : JsonConvert.SerializeObject(new { formid, data }));
    }
}
